﻿using ERP.Inventory.Infastructure.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ERP.Inventory.Infastructure.Impelment
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private readonly MyDbContext db;

        public BaseRepository(MyDbContext db)
        {
            this.db = db;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="t">实体类</param>
        /// <returns>返回受影响的行数</returns>
        public async Task<int> Add(T t)
        {
            //异常处理
            try
            {
                await db.Set<T>().AddAsync(t);
                return await db.SaveChangesAsync();
            }
            catch (Exception)
            {

                throw;
            }
        }

        public async Task<int> AddRange(List<T> list)
        {
            //异常处理
            try
            {
                 db.Set<T>().AddRange(list);
                return await db.SaveChangesAsync();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 显示全部
        /// </summary>
        /// <returns>返回受影响的行数</returns>
        public IQueryable<T> GetAll()
        {
            //异常处理
            try
            {
                return db.Set<T>();
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 查询一个
        /// </summary>
        /// <param name="id">id</param>
        /// <returns>返回受影响的行数</returns>
        public async Task<T> GetValue(int id)
        {
            //异常处理
            try
            {
                return await db.Set<T>().FindAsync(id);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="t">实体类</param>
        /// <returns>返回受影响的行数</returns>
        public async Task<int> Update(T t)
        {
            //异常处理
            try
            {
                db.Set<T>().Update(t);
                return await db.SaveChangesAsync();
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
